package com.xbongbong.workflow.service.operator.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.pojo.workflow.WorkflowDataPojo;
import com.xbongbong.paas.pojo.workflow.WorkflowExplainPojo;
import com.xbongbong.paas.pojo.workflow.WorkflowSubDataPoJo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.util.WorkflowExplainUtil;
import com.xbongbong.paas.util.WorkflowUtil;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.workflow.WorkflowValueTypeEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.workflow.domain.entity.WorkflowNodeEntity;
import com.xbongbong.workflow.pojo.WorkflowOperationsPojo;
import com.xbongbong.workflow.pojo.WorkflowTransferPOJO;
import com.xbongbong.workflow.pojo.nodes.InsertRecordNode;
import com.xbongbong.workflow.service.operator.WorkflowOperatorMainAndSubFormService;
import com.xbongbong.workflow.service.operator.WorkflowOperatorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 此方法主要是用来解决子表单字段赋值给主字段
 * @author 吴峰
 * @date 2021/06/24 9:45
 */
@Service("workflowOperatorSubFormServiceImpl")
public class WorkflowOperatorSubFormServiceImpl implements WorkflowOperatorMainAndSubFormService<JSONObject> {

    private static final Logger LOGGER = LoggerFactory.getLogger(WorkflowOperatorSubFormServiceImpl.class);

    @Resource
    private Map<Integer, WorkflowOperatorService>  workflowOperatorMap;


    @Override
    public JSONObject getInsertFieldListByDataNode(WorkflowOperationsPojo workflowOperationsPojo, WorkflowExplainPojo workflowExplainPojo, FieldAttrEntity targetField,
                                                   Map<Long, PaasFormDataEntityExt> formDataMap, Map<Long, JSONObject> dataMap, InsertRecordNode insertRecordNode,
                                                   WorkflowNodeEntity workflowNodeEntity, WorkflowDataPojo workflowDataPojo, WorkflowTransferPOJO workflowTransferPojo) throws XbbException {
        try {
            JSONObject result = new JSONObject();
            Map<String, Map<String, WorkflowOperationsPojo>>  targetSubOperator = workflowExplainPojo.getTargetSubOperator();
            Map<Long, Map<String, Map<String, FieldAttrEntity>>> subExplainMap = workflowExplainPojo.getSubExplainMap();
            Map<Long, Map<String, Map<String, FieldAttrEntity>>> workOrderSubExplainMap = workflowExplainPojo.getWorkOrderSubExplainMap();


            WorkflowSubDataPoJo workflowSubDataPoJo = WorkflowUtil.getSubData(workflowOperationsPojo, workflowTransferPojo.getData().getNodeId(), formDataMap);
            JSONArray subDataArray = workflowSubDataPoJo.getSubData();
            if (Objects.nonNull(subDataArray) && !subDataArray.isEmpty()) {
                String targetAttr = ExplainUtil.getAttrByPoint(workflowOperationsPojo.getAttr()).get(0);
                JSONArray subResultList = new JSONArray();
                for (int i = 0; i < subDataArray.size(); i++) {
                    Iterator<String> subOperatorIterator = targetSubOperator.get(targetAttr).keySet().iterator();
                    JSONObject resultJson = new JSONObject();
                    while (subOperatorIterator.hasNext()) {
                        String subKey = subOperatorIterator.next();
                        workflowOperationsPojo = targetSubOperator.get(targetAttr).get(subKey);
                        List<String> targetAttrList = ExplainUtil.getAttrByPoint(workflowOperationsPojo.getAttr());
                        FieldAttrEntity targetSubField = WorkflowExplainUtil.getTargetSubField(workOrderSubExplainMap, subExplainMap, workflowNodeEntity,
                                targetAttrList.get(0), targetAttrList.get(1));
                        String thisAttr = workflowOperationsPojo.getValueAttr();
                        String thisSubAttr = "";
                        List<String> thisAttrList = ExplainUtil.getAttrByPoint(workflowOperationsPojo.getValueAttr());
                        if (Objects.equals(WorkflowValueTypeEnum.DYNAMIC_VALUE.getType(), workflowOperationsPojo.getValueType()) && thisAttrList.size() == BasicConstant.TWO) {
                            thisAttr = thisAttrList.get(0);
                            thisSubAttr = thisAttrList.get(1);

                        }
                        WorkflowOperatorService workflowOperatorService = workflowOperatorMap.get(workflowOperationsPojo.getValueType());
                        // 获取字段解释，可能为null，只有动态值才有字段，公式和固定值是无固定的字段的
                        FieldAttrEntity fieldAttrEntity = WorkflowExplainUtil.getThisSubField(workOrderSubExplainMap, subExplainMap, workflowOperationsPojo.getFormId(),
                                workflowOperationsPojo.getBusinessType(), workflowOperationsPojo.getValueType(), thisAttr, thisSubAttr);

                        dataMap.put(workflowSubDataPoJo.getNodeId(), subDataArray.getJSONObject(i));

                        Object value = workflowOperatorService.operatorByInsertNodeSourceData(workflowNodeEntity, fieldAttrEntity, targetSubField,  formDataMap,
                                dataMap, workflowOperationsPojo, workflowDataPojo, workflowTransferPojo, workflowExplainPojo);
                        resultJson.put(subKey, value);
                    }
                    subResultList.add(resultJson);
                    result.put(targetAttr, subResultList);
                }
            }
            return result;
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOGGER.error("WorkflowOperatorSubFormServiceImpl.getInsertFieldListByDataNode error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public Object getUpdateData(WorkflowOperationsPojo workflowOperationsPojo, WorkflowExplainPojo workflowExplainPojo, FieldAttrEntity targetField, Map<Long, PaasFormDataEntityExt> workflowDataMap,
                                Map<Long, JSONObject> dataMap, WorkflowNodeEntity workflowNodeEntity, WorkflowDataPojo workflowDataPojo, WorkflowTransferPOJO workflowTransferPojo) throws XbbException {
        try {
            Map<Long, Map<String, Map<String, FieldAttrEntity>>> subExplainMap = workflowExplainPojo.getSubExplainMap();
            Map<Long, Map<String, Map<String, FieldAttrEntity>>> workOrderSubExplainMap = workflowExplainPojo.getWorkOrderSubExplainMap();
            // 获取目标表单字段
            List<String> targetAttrList = ExplainUtil.getAttrByPoint(workflowOperationsPojo.getAttr());
            FieldAttrEntity targetSubField = WorkflowExplainUtil.getTargetSubField(workOrderSubExplainMap, subExplainMap, workflowNodeEntity,
                    targetAttrList.get(0), targetAttrList.get(1));
            // 获取字段解释，可能为null，只有动态值才有字段，公式和固定值是无固定的字段的
            List<String> thisAttrList = ExplainUtil.getAttrByPoint(workflowOperationsPojo.getValueAttr());
            String thisAttr = workflowOperationsPojo.getValueAttr();
            String thisSubAttr = "";
            // 获取子表单外字段
            FieldAttrEntity fieldAttrEntity = WorkflowExplainUtil.getThisField( workflowDataPojo.getExplainMap(), workflowOperationsPojo.getFormId(),
                    workflowOperationsPojo.getBusinessType(), workflowOperationsPojo.getValueType(), thisAttr);
            if (Objects.equals(WorkflowValueTypeEnum.DYNAMIC_VALUE.getType(), workflowOperationsPojo.getValueType()) && thisAttrList.size() == BasicConstant.TWO) {
                // 获取子表单字段
                thisAttr = thisAttrList.get(0);
                thisSubAttr = thisAttrList.get(1);
                fieldAttrEntity = WorkflowExplainUtil.getThisSubField(workOrderSubExplainMap, subExplainMap,
                        workflowOperationsPojo.getFormId(), workflowOperationsPojo.getBusinessType(),
                        workflowOperationsPojo.getValueType(), thisAttr, thisSubAttr);
            }

            WorkflowOperatorService workflowOperatorService = workflowOperatorMap.get(workflowOperationsPojo.getValueType());
            return workflowOperatorService.operatorByUpdateNode(workflowNodeEntity,  fieldAttrEntity, targetSubField, workflowDataMap,
                    dataMap, workflowOperationsPojo, workflowDataPojo, workflowTransferPojo, workflowExplainPojo);
        } catch (XbbException e) {
            LOGGER.error("WorkflowOperatorSubFormServiceImpl.getUpdateData error", e);
            throw e;
        } catch (Exception e) {
            LOGGER.error("WorkflowOperatorSubFormServiceImpl.getUpdateData error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }
}
